package cn.yr.clock.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.yr.clock.domain.enmu.EngineEnum;
import cn.yr.clock.domain.entity.Engine;
import cn.yr.clock.domain.entity.EnginePrizeRel;
import cn.yr.clock.domain.entity.Prize;
import cn.yr.clock.domain.entity.PrizeInstance;
import cn.yr.clock.handler.EngineHandler;
import cn.yr.clock.mapper.PrizeMapper;
import cn.yr.clock.service.EnginePrizeRelService;
import cn.yr.clock.service.PrizeInstanceService;
import cn.yr.clock.service.PrizeService;
import cn.yr.common.exception.ret.Ret;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service("prizeService")
public class PrizeServiceImpl extends ServiceImpl<PrizeMapper, Prize> implements PrizeService {

    @Autowired
    private PrizeMapper prizeMapper;

    @Autowired
    private PrizeInstanceService prizeInstanceService;
    @Autowired
    private EnginePrizeRelService enginePrizeRelService;
    @Autowired
    private EngineHandler engineHandler;


    @Override
    @Transactional
    public Ret receivePrice(Engine engine, Long userId) {
        QueryWrapper<EnginePrizeRel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("engine_id", engine.getEngineId());
        if (EngineEnum.Cycle.getType().equals(engine.getEngineType())) {
            queryWrapper.eq("rounds",engineHandler.getCycleRounds(userId));
        }
        EnginePrizeRel prizeRel = enginePrizeRelService.getOne(queryWrapper, false);
        if (ObjectUtil.isNull(prizeRel)) {
            return Ret.error("抱歉 您暂时未获得该领奖资格");
        }
        if(ObjectUtil.isNotNull(prizeRel.getPrizeInstanceId())){
            return Ret.error("抱歉 您已经领取过该奖品");
        }
        PrizeInstance prizeInstance = prizeInstanceService.getPrizeInstanceServiceByPrizeId(engine.getPrizeId());
        if (ObjectUtil.isNull(prizeInstance)) {
            return Ret.error("抱歉 奖券库存不足");
        }
        //标记领奖人
        prizeInstance.setUserId(userId);
        prizeInstance.setCreateTime(new Date());
        prizeInstanceService.updateById(prizeInstance);

        EnginePrizeRel enginePrizeRel = new EnginePrizeRel();
        //标记已领将
        enginePrizeRel.setStatus(1);
        enginePrizeRel.setReceiveTime(new Date());
        enginePrizeRel.setPrizeInstanceId(prizeInstance.getPrizeInstanceId());
        QueryWrapper<EnginePrizeRel> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("prize_id", engine.getPrizeId());
        wrapper.eq("engine_id", engine.getEngineId());
        enginePrizeRelService.update(enginePrizeRel, wrapper);


        return Ret.success(prizeInstance);
    }
}